import nProgress from 'nprogress'; //引入进度条
import 'nprogress/nprogress.css'; //引入进度条样式

import { createRouter, createWebHistory } from 'vue-router';
import { type RouteRecordRaw } from 'vue-router'; //引入路由类型

import { type MenuItem } from '@/store/modules/user-info'; //引入 store(pinia) 用户信息模块,菜单类型定义
import { buildDynamicRoutes, type RouterMap } from './dynamic-router';

import SmartLayout from '@/layout/index.vue'; //引入首页布局组件
import NotFound from '@/views/40X/404.vue'; //引入404页面
import NoPrivilege from '@/views/40X/403.vue'; //引入403页面

import { LocalStorage } from '@/utils/utils';
import { isTokenExpired } from '@/utils/token';
import { forEach } from 'lodash-es';
import { TagNavStore } from '@/store/modules/tag-nav';

/* 定义(登录页)静态路由 */
const loginRoutes: Array<RouteRecordRaw> = [
  {
    path: '/admin_login',
    name: 'AdminLogin',
    component: () => import('@/views/login/admin.vue'),
    meta: {
      title: '总后台登录',
      hideInMenu: true,
    },
  },
  {
    path: '/agent_login',
    name: 'AgentLogin',
    component: () => import('@/views/login/admin.vue'),
    meta: {
      title: '代理商登录',
      hideInMenu: true,
    },
  },
  {
    path: '/customer_login',
    name: 'CustomerLogin',
    component: () => import('@/views/login/admin.vue'),
    meta: {
      title: '客户经理登录',
      hideInMenu: true,
    },
  },
  {
    path: '/merchant_login',
    name: 'MerchantLogin',
    component: () => import('@/views/login/admin.vue'),
    meta: {
      title: '商户登录',
      hideInMenu: true,
    },
  },
];
/* 定义(首页)静态路由 */
export const homeRouters: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: '_home',
    redirect: '/home',
    component: SmartLayout,
    meta: {
      title: '首页',
      menuType: 1, //目录
      icon: 'HomeOutlined',
    },
    children: [
      {
        path: '/home',
        name: 'Home',
        meta: {
          title: '首页',
          menuType: 2, //菜单
          icon: 'HomeOutlined',
          parentMenuList: [{ name: '_home', title: '首页' }],
        },
        component: () => import('@/views/home.vue'),
      },
    ],
  },
];
/* 定义(40X)静态路由,无权限访问、找不到页面 */
export const x40Routers: Array<RouteRecordRaw> = [
  { path: '/403', name: '403', component: NoPrivilege },
  { path: '/:pathMatch(.*)*', name: '404', component: NotFound },
];

/* 定义(静态路由)数组 */
const routeArray = [...loginRoutes, ...homeRouters, ...x40Routers];

/* 创建路由实例 */
export const router = createRouter({
  history: createWebHistory(),
  routes: routeArray,
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

// 动态添加路由（需在用户登录后执行，如路由守卫中）
export function buildRoutes(menuList: MenuItem[]) {
  /* 调用路由构建函数，构建动态路由 */
  const dynamicRoutes = buildDynamicRoutes(menuList);
  //console.log("动态路由:", dynamicRoutes);
  /* 添加内部 40x 路由 */
  forEach(x40Routers, (route) => {
    dynamicRoutes.push(route as RouterMap);
  });

  router.addRoute({
    path: '/',
    meta: {},
    component: SmartLayout,
    children: dynamicRoutes,
  });
}

// 路由守卫：登录后添加动态路由
router.beforeEach((to, from, next) => {
  // 进度条开启
  nProgress.start();
  //console.log("路由守卫:", to, from);
  if (to.name === '403' || to.name === 'AdminLogin') {
    //403、404页面，放行
    next();
    return;
  }
  /* 检查是否存在 token、token 是否过期 */
  const token = LocalStorage.get('token');
  const loginName = LocalStorage.get('loginName'); //登录页路径
  let isLogin = false; //是否登录 标识
  if (!token) {
    //没有token，未登录
    isLogin = false;
  } else if (!isTokenExpired(token)) {
    //token 未过期，已登录
    isLogin = true;
  }

  if (!isLogin) {
    //未登录
    if (loginName) {
      //有登录页，跳转到登录页
      next({ name: loginName });
    } else {
      //无登录页，跳转到 403 页面
      next({ name: '403' });
    }
    return;
  } else {
    //已登录
    if (to.name === '404') {
      //登录页，跳转到首页
      next(to.path);
      return;
    } else {
      /* 检查该菜单是否有权限 */
    }
  }

  // 设置tagNav
  //console.log("路由守卫：设置tagNav");
  TagNavStore().setTagNav(to, from);
  next();
});

router.afterEach(() => {
  nProgress.done();
});
